extends Node

var configRootPath = "res://Assets/Configs/CSV/"

func loadCSV(filePath):
	var file = FileAccess.open(filePath, FileAccess.READ)
	var data = []
	
	if not file:
		print("文件不存在：" + filePath)
		return null
		
	while not file.eof_reached():
		var line = file.get_csv_line()
		if line.size() > 0 and not (line.size() == 1 and line[0] == ""):
			data.append(line)
			
	file.close()
	
	return data
	

func pathJoin(path1:String, path2:String):
	if path1.ends_with("/"):
		return path1 + path2
	else:
		return path1 + "/" + path2
		

func parseCSV(data:Array, clz):
	var result = []
	var configs = []
	var configsDict = {}
	
	if data.size() < 2:
		print("CSV文件内容不正确", data)
		return null
		
	var headers = data[0]
	for i in range(1, data.size()):
		var line = data[i]
		if line.size() == 0:
			continue
			
		var inst = clz.new()
		for j in range(line.size()):
			var field = headers[j]
			inst.set(field, str(line[j]))
		
		configs.append(inst)
		configsDict[line[0]] = inst
	
	result.append(configs)
	result.append(configsDict)
		
	return result


func loadConfig(csvFileName, clz):
	var data:Array = loadCSV(pathJoin(configRootPath, csvFileName))
	var result = parseCSV(data, clz)
	if result:
		clz.configArr = result[0]
		clz.idConfigDict = result[1]
		if clz.has_method("processData"):
			clz.processData()
